/**
 * @file comp_misc_lib.c
 * @author Blues Jiang (jiangrn@breo.com.cn)
 * @brief
 * @version 0.1
 * @date 2021-12-28
 *
 * @copyright Copyright (c) 2021
 *
 */

#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "comp_misc_lib.h"

/**
 * @brief   string to hexadecimal.
 *
 * @param   src is source string.
 *
 * @param   src is source string length.
 *
 * @param   dest is target array.
 *
 * @param   dest_len is target array length.
 *
 */
int str_to_hex(const char *src, int src_len, uint8_t *dest,
               int dest_len)
{
    if (dest_len < (src_len / 2))
    { return -1; }

    char h1, h2;
    char s1, s2;
    int i;

    for (i = 0; i < src_len / 2; i++)
    {
        h1 = src[2 * i];
        h2 = src[2 * i + 1];
        s1 = toupper(h1) - 0x30;

        if (s1 > 9)
        { s1 -= 7; }

        s2 = toupper(h2) - 0x30;

        if (s2 > 9)
        { s2 -= 7; }

        dest[i] = s1 * 16 + s2;
    }

    return src_len / 2;
}

/**
 * @brief   string to hexadecimal.
 *
 * @param   src is source string.
 *
 * @param   src is source string length.
 *
 * @param   dest is target array.
 *
 * @param   dest_len is target array length.
 *
 */
int hex_to_str(const uint8_t *src, int src_len, char *dest,
               int dest_len)
{
    if (dest_len < (src_len * 2))
    { return -1; }

    char ddl, ddh;

    for (int i = 0; i < src_len; i++)
    {
        ddh = 48 + src[i] / 16;
        ddl = 48 + src[i] % 16;

        if (ddh > 57) { ddh = ddh + 7; }

        if (ddl > 57) { ddl = ddl + 7; }

        dest[i * 2] = ddh;
        dest[i * 2 + 1] = ddl;
    }

    dest[src_len * 2] = '\0';
    return src_len * 2;
}

